package com.att.device;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.IShellOutputReceiver;
import com.android.ddmlib.InstallException;
import com.android.ddmlib.ShellCommandUnresponsiveException;
import com.android.ddmlib.TimeoutException;

public class AttMain {
	private Map<String, IDevice> map;
	private int port = 12346;
	private String apk;
	
	public void waitForConnect(AndroidDebugBridge adb) throws InterruptedException {
		while (!adb.hasInitialDeviceList()) {
			Thread.sleep(100);
		}
	}
	
	public void getDevices() throws InterruptedException {
		AndroidDebugBridge adb = AndroidDebugBridge.createBridge();
		waitForConnect(adb);
		map = new HashMap<String, IDevice>();
		IDevice[] devices = adb.getDevices();
		for (IDevice device : devices) {
			map.put(device.getSerialNumber(), device);
		}
	}
	
	public boolean checkApkIsInstalled(IDevice device) throws IOException, TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException {
		String cmd = "cd /data/data/com.att.app/";
		CheckApkReceiver rec  = new CheckApkReceiver();
		device.executeShellCommand(cmd, rec);
		return rec.InstalledApk;
	}
	
	public void installApk(IDevice device) throws IOException, InstallException {
		device.installPackage(apk, true);
	}
	
	
	public void startApk(IDevice device) throws IOException, InterruptedException, TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException {
//		String cmd = "am start -n com.att.app/.AttActivity";
		String cmd = "am startservice -a att.intent.device";
		StartApkReceiver rec  = new StartApkReceiver();
		device.executeShellCommand(cmd, rec);
		Thread.sleep(1000);
	}
	
	public String getDeviceInfoBySocket(IDevice device) throws UnknownHostException, IOException {
		Socket socket = new Socket("127.0.0.1", port);
		BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		String info = br.readLine();
//		System.out.println("@" + device.getSerialNumber() + "|" + info);
		if (!socket.isClosed()) {
			socket.close();
		}
		return info.replaceFirst("@", device.getSerialNumber());
	}
	
//	public static void main(String[] args) {
//		System.out.println("start");
//		AttMain att = new AttMain();
//		if (args.length == 1) {
//			att.apk = args[0];
//		} else if (args.length == 2) {
//			att.apk = args[0];
////			att.port = Integer.valueOf(args[1]);
//		}
//		
//		Scanner scanner = new Scanner(System.in);
//		while (true) {
//			String cmd = scanner.nextLine();
//			if (cmd.equals("devices")) {
//				try {
//					att.getDevices();
//					StringBuilder sb = new StringBuilder();
//					sb.append("<devices>");
//					for (Map.Entry<String, IDevice> entry : att.map.entrySet()) {
//						sb.append("<sn>");
//						sb.append(entry.getValue().getSerialNumber());
//						sb.append("</sn>");
////						System.out.println("@devices_" + entry.getValue().getSerialNumber());
////						System.out.println("@devices_ok");
////						entry.getValue().executeShellCommand("getprop", new IShellOutputReceiver() {
////							
////							@Override
////							public boolean isCancelled() {
////								return false;
////							}
////							
////							@Override
////							public void flush() {
////							}
////							
////							@Override
////							public void addOutput(byte[] b, int offset, int length) {
////								String result = new String(b, offset, length);
////								Pattern pattern = Pattern.compile("[ro.product.model]");
////								Matcher matcher = pattern.matcher(result);
////								if(matcher.find())
////									  
////							}
////						});
//					}
//					sb.append("</devices>");
//					System.out.println(sb.toString());
//				} catch (InterruptedException e) {
//					e.printStackTrace();
//				} 
//				continue;
//			}
//			if (cmd.equals("devices info all")) {
//				StringBuilder sb = new StringBuilder();
//				sb.append("<devices>");
//				for (Map.Entry<String, IDevice> entry : att.map.entrySet()) {
//					IDevice device = entry.getValue();
//					device.createForward(att.port, att.port);
//					try {
//						if (!att.checkApkIsInstalled(device)) {
//							att.installApk(device);
//						}
//						att.startApk(device);
//						String result = att.getDeviceInfoBySocket(device);
////						System.out.println("@devices_info_all_" + result);
////						System.out.println("@devices_info_all_ok");
//						sb.append(result);
//					} catch (IOException e) {
//						e.printStackTrace();
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//					sb.append("</devices>");
//					System.out.println(sb.toString());
//				}
//			}
//			if (cmd.contains("single device")){
//				String sn = cmd.substring(cmd.lastIndexOf(" ") + 1, cmd.length());
////				System.out.println(sn);
//				IDevice device = att.map.get(sn.trim());
//				if (device == null) {
//					System.out.println("can not find the device");
//				} else {
//					device.createForward(att.port, att.port);
//					try {
//						if (!att.checkApkIsInstalled(device)) {
//							att.installApk(device);
//						}
//						att.startApk(device);
//						StringBuilder sb = new StringBuilder();
//						sb.append("<devices>");
//						String result = att.getDeviceInfoBySocket(device);
//						sb.append(result);
//						sb.append("</devices>");
//						System.out.println(sb.toString());
////						System.out.println("@single_device_" + result);
////						System.out.println("@single_device_ok");
//					} catch (IOException e) {
//						e.printStackTrace();
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//			if (cmd.equals("quit")) {
//				System.exit(0);
//			}
//		}
//	}
	
}
